# -*- encoding: utf-8 -*-

import time
import codecs
import os

import appuifw
import inbox

in_box = inbox.Inbox()
sent_box = inbox.Inbox(inbox.ESent)

contacts = []
sms_ids = []


# SMS Item
# id for sms id
# time for sort
# box for where the sms coms from
class SMSItem(object):
    def __init__(self, sid, stime, sbox):
        self.id = sid
        self.time = stime
        self.box = sbox


# Process a sms box
# add item as a SMSItem to sms list
def process_box(box):
    global contacts, sms_ids    
    for sid in box.sms_messages():
        addr = box.address(sid)
        try:
            idx = contacts.index(addr)
        except ValueError:
            contacts.append(addr)
            idx = len(contacts) - 1
            sms_ids.append([])

        sms_ids[idx].append(SMSItem(sid, box.time(sid), box))



process_box(in_box)
process_box(sent_box)

day_str = time.strftime("%Y%m%d")
os.mkdir("e:\\Others\\sms_bk%s" % day_str)

for idx, val in enumerate(contacts):
    sms_ids[idx].sort(cmp=lambda x, y: cmp(x.time, y.time))
    f = codecs.open("e:\\Others\\sms_bk%s\\%s_%s.txt" % \
        (day_str, val, day_str), "w", "utf8")
    for i in sms_ids[idx]:
        if i.box == in_box:
            f.write(u"%s - %s\r\n" % (val, time.ctime(i.time)))
        else:
            f.write(u"我 - %s\r\n" % time.ctime(i.time))
        f.write(u"  %s\r\n" % i.box.content(i.id))        
    f.close()

appuifw.note(u"SMS backup OK!")
